import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask import redirect
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf
from redis import StrictRedis
from werkzeug.routing import BaseConverter

from config import config_dict

redis_store = None

db = SQLAlchemy()

class HTMLConverter(BaseConverter):
    regex = '.*'

def create_app(config_name):


    #判断参数是否合法
    if config_name not in config_dict:
        raise Exception("传递的参数有误")

    app = Flask(__name__)

    config = config_dict[config_name]

    log_file(config.LEVEL)

    app.url_map.converters["html"] = HTMLConverter

    # 加载配置信息到app中
    app.config.from_object(config)

    # 创建SQLAlchemy,关联app
    db.init_app(app)

    # 创建redis对象
    global redis_store
    redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT,decode_responses=True)

    # 创建Session对象,读取app中的session信息
    Session(app)

    # 创建CSRFProtect,保护app
    # CSRFProtect(app)

    #使用请求钩子拦截所有的请求
    @app.after_request
    def set_csrf_token(response):
        #获取csrf_token
        csrf_token = generate_csrf()
        #设置csrf_token到cookie中
        response.set_cookie("csrf_token",csrf_token)
        #返回响应
        return response


    #蓝图的注册
    from ihome_tenancy.modules.html_views import html_blueprint
    app.register_blueprint(html_blueprint)

    from ihome_tenancy.modules.user_views import user_blueprint
    app.register_blueprint(user_blueprint, url_prefix='/api/v1')

    from ihome_tenancy.modules.house_view import house_blueprint
    app.register_blueprint(house_blueprint,url_prefix='/api/v1')

    from ihome_tenancy.modules.order_views import order_blueprint
    app.register_blueprint(order_blueprint,url_prefix='/api/v1')
    print(app.url_map)
    return app


def log_file(LEVEL):
    # 设置日志的记录等级
    logging.basicConfig(level=LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)